﻿using BZ.Logger;
using HalconDotNet;
using NDK.Module.Model;
using NDK.Motion.BLL;
using NDK.Motion.MachineManager;
using NDK.Motion.Monitor;
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace NDK.Module.StationLogic
{
    public class Station_转盘三穴 : StationLogic
    {
        #region 通用
        public override event PropertyChangedEventHandler PropertyChanged;

        public static Station_转盘三穴 Instance = new Station_转盘三穴();
        public ConcurrentQueue<string> CTQueue;
        public Stopwatch SunWay03 = new Stopwatch();
        public string StationName = "Station03转盘3工位";

        private bool isLaserFail;

        //步骤字段、属性
        private StationStep _Step = StationStep.扫描轴运行至起始位;
        [Monitor(Description = "当前步骤")]
        public StationStep Step
        {
            get
            {
                return _Step;
            }
            set
            {
                if (_Step != value)
                {
                    if (!Common.BP_是否屏蔽计时)
                    {
                        WriteStationCTLog("StationCTLog", $"{_Step}用时为：{swStepTime.ElapsedMilliseconds} ms");
                        swStepTime.Restart();
                    }
                    _Step = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(value.ToString()));
                }
            }
        }
        public HImage image1;
        public HImage image2;
        public HImage image3;
        #endregion

        /// <summary>
        /// 工站初始化
        /// </summary>
        public override void Init()
        {
            base.Init();
            StationID = 3;
            CurHoleId = 7;
            logBaseInfo = "转盘三穴流程";
            Step = StationStep.扫描轴运行至起始位;
            FlowCT = new Stopwatch();
            CTQueue = new ConcurrentQueue<string>();
            MVCCD = Common.HikVisionList[1];
            QueueSN = new ConcurrentQueue<string>();
            QueueImage = new ConcurrentQueue<MeasureImage>();

            VisionFlowName = $"上Laser_{Common.CurProType}";
        }


        public override void ActionProcess()
        {
            try
            {
                switch (Step)
                {
                    case StationStep.扫描轴运行至起始位:
                        if (MotionControl.AxesMove(Machine.pos_激光扫描起始位_转盘工位三))
                        {
                            isLaserFail = false;
                            Step = StationStep.判断是否工作;
                        }
                        SunWay03.Restart();
                        break;

                    case StationStep.判断是否工作:
                        if (!Common.AllStationCanWork)
                            break;
                        if (!Common.DicStationWorkStatus[StationID])
                        {
                            Step = Common.DicHoleCanWork[CurHoleId] ? StationStep.触发激光开始扫描 : StationStep.工位流程完成;
                        }
                        break;

                    case StationStep.触发激光开始扫描:
                        if (!Common.IsEmptyModel)
                        {
                            Common.SSZN_上激光.Start();
                        }
                        MotionControl.AxesMoveNoWait(Machine.pos_激光扫描终点位_转盘工位三);
                        Step = isLaserFail ? StationStep.等待激光扫描完成 : StationStep.触发相机拍照取图1;
                        break;

                    case StationStep.触发相机拍照取图1:
                        if (Common.CurProType != "Product" && Common.CurProType != "Product1")
                        {
                            Machine.imageAllLight[CurHoleId - 1].Open();
                        }
                        Machine.imageLights_三工站蓝光光源.OpenAll();
                        Thread.Sleep(Common.IP_光源延时);
                        if (Common.IsEmptyModel)
                        {
                            Thread.Sleep(1000);
                            Step = StationStep.等待激光扫描完成;
                        }
                        else if (CCDImage(ref HImageCCD))
                        {
                            image1 = HImageCCD.Clone();
                            Step = Common.CurProType.Contains("Product") ? StationStep.触发相机拍照取图2 : StationStep.等待激光扫描完成;
                        }

                        if (Common.CurProType != "Product" || Common.CurProType != "Product1")
                        {
                            Machine.imageAllLight[CurHoleId - 1].Close();
                            Machine.imageLights_三工站蓝光光源.Close();
                        }
                        break;

                    case StationStep.触发相机拍照取图2:
                        Machine.imageLights_三工站蓝光光源2.OpenAll();
                        Thread.Sleep(Common.IP_光源延时);
                        {
                            if (CCDImage(ref HImageCCD))
                            {
                                image2 = HImageCCD.Clone();
                                Step = StationStep.触发相机拍照取图3;
                            }
                        }
                        //Machine.imageLights_三工站蓝光光源2.Close();
                        break;

                    case StationStep.触发相机拍照取图3:
                        Machine.imageLights_三工站蓝光光源3.OpenAll();
                        Thread.Sleep(Common.IP_光源延时);
                        {
                            if (CCDImage(ref HImageCCD))
                            {
                                image3 = HImageCCD.Clone();
                                Step = StationStep.等待激光扫描完成;
                            }
                        }
                        Machine.imageLights_三工站蓝光光源3.CloseAll();
                        Machine.imageAllLight[CurHoleId - 1].Close();
                        break;

                    case StationStep.等待激光扫描完成:
                        if (MotionControl.AxesMove(Machine.pos_激光扫描终点位_转盘工位三))
                        {
                            Step = Common.IsEmptyModel ? StationStep.调用算法计算 : StationStep.获取激光扫描图片;
                        }
                        break;

                    case StationStep.获取激光扫描图片:
                        var image = Common.SSZN_上激光.HeightImage(3000);
                        if (image != null)
                        {
                            isLaserFail = false;
                            Station_转盘二穴.Instance.QueueSN.TryDequeue(out var sn);
                            QueueSN.Enqueue(sn);
                            (string, HImage)[] images;
                            if (Common.CurProType.Contains("Product"))
                            {
                                images = new (string, HImage)[] { ("上激光", image), ("侧CCD1", image1), ("侧CCD2", image2), ("侧CCD3", image3) };
                            }
                            else
                            {
                                images = new (string, HImage)[] { ("上激光", image), ("侧CCD1", image1) };
                            }
                            QueueImage.Enqueue(new MeasureImage() { Hole = CurHoleId, Images = images });
                            DataProcess.Instance.VisionProcessAsync($"上Laser_{Common.CurProType}", $"上Laser_{Common.CurProType}Data", CurHoleId, sn, images[0]);
                            Step = StationStep.调用算法计算;
                        }
                        else
                        {
                            isLaserFail = true;
                            Step = StationStep.扫描轴运行至起始位;
                            Common.SSZN_上激光.StopAcqHeightImage();
                            Common.SSZN_上激光.Connect(Common.SP_工位3_深视上激光IP);
                            if (AlarmPause("激光出图异常", $"三工站激光出图异常，请检查", "重新检测", "忽略报警，继续运行") == DialogResult.OK)
                            {

                            }
                        }
                        Common.SSZN_上激光.Stop();
                        break;

                    case StationStep.调用算法计算:
                        Step = StationStep.工位流程完成;
                        break;

                    case StationStep.工位流程完成:
                        CurHoleId++;
                        if (CurHoleId > 8)
                        {
                            CurHoleId = 1;
                        }
                        Common.ChangeTurnTableStatus(StationID, true);
                        Step = StationStep.扫描轴运行至起始位;
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                UILog_Error($"[{logBaseInfo}] {ex.Message}");
            }
        }

        public override void EmptyActionProcess()
        {
            ActionProcess();
        }

        public override void GRRActionProcess()
        {
            ActionProcess();
        }

        public enum StationStep
        {
            扫描轴运行至起始位,
            判断是否工作,
            触发激光开始扫描,
            触发相机拍照取图1,
            触发相机拍照取图2,
            触发相机拍照取图3,
            等待激光扫描完成,
            获取激光扫描图片,
            调用算法计算,
            工位流程完成
        }
    }
}
